import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Resources} from "./resources";
import {Router, ActivatedRoute} from "@angular/router";
import {ResourcesService} from "./resources.service";
import {ResponseUtil} from "../../../util/response-util";
import {MsgResult} from "../../../models/msg-result";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {API, MsgConstants} from "../../../constants/constants";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {TableUtil} from "../../../util/table-util";

declare  var $;

@Component({
  selector: 'app-resources',
  templateUrl: './resources.component.html'
})
export class ResourcesComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  //存储初始化表单数据
  resources : Resources[];
  //声明id
  id:string =null;
  resourceId : string = null;

  table;

  constructor(
    private route :Router,
    private router : ActivatedRoute,
    private resourcesService : ResourcesService,
    private pageSubject : PageSubject,
    private tableUtil:TableUtil,
    private dialogService : OneDialogService,
    private response :ResponseUtil
  ) {  }

  proxy = {
    "resourceAdd": () => this.resourceAdd(),
    "resourceUpdate": () => this.resourceUpdate(),
    "resourceDelete": () => this.resourceDelete()
  }
  ngOnInit() {
    this.pushPage();
    this.loadResources();
  }
  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("资源管理","查询",path);
  }

  /**
   * 添加页面跳转
   */
  resourceAdd(){
    this.route.navigate(['add'],{relativeTo : this.router});
  }


  /**
   * 实现删除弹窗
   */
  resourceDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    if (rows.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.resourceId = rows[0].id;
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }
  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    this.resourcesService.deleteResource(this.resourceId).subscribe(
      result => this.response.success(result, this.processDeleteResult),
      error => this.response.error(error)
    );
  }
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  search() {
    this.table.bootstrapTable('refresh');
  }


  /**
   * 修改页面跳转传参
   */
  resourceUpdate(){
    let rows = this.table.bootstrapTable('getSelections');
    if (rows.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      let resourcesId = rows[0].id;
      this.route.navigate(['update', {resourcesId: resourcesId}], {relativeTo: this.router});
    }
  }

  /**
   * 资源查询
   */
  loadResources() {
    this.table = this.tableUtil.load("one_table_resource",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '资源名称', align: 'left', switchable: false},
        {field: "url", title: 'URL', align: 'left'},
        {field: "isValid", title: '有效', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isShow", title: '显示', align: 'left', formatter: this.yesOrNoFormat},
        {field: "creatorName", title: '创建人', align: 'left',visible: false},
        {field: "create_date", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true ,visible: false},
        {field: "editorName", title: '修改人', align: 'left', visible: false},
        {field: "modified_date", title: '修改日期', align: 'left', sortName: "CREATE_DATE", sortable: true, visible: false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: true,//单选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_resources",
      url: API.resourcesPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#resourceName").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          // console.log(JSON.stringify(result));
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.modified_date = value.modifiedDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'MODIFIED_DATE',
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }
}
